package com.qg.auth.handler.impl;

import cn.hutool.core.bean.BeanUtil;
import com.qg.auth.handler.WebContextHandler;
import com.qg.auth.properties.QgAuthProperties;
import com.qg.base.constants.WebConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author QG
 * @Date 2023/5/25 14:09
 * @description 基于redis的token实现
 **/
@Component("webContextHandler")
@ConditionalOnBean(RedisTemplate.class)
@ConditionalOnProperty(name = "system.login.method", havingValue = "redis", matchIfMissing = false)
public class WebContextToeknRedis implements WebContextHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebContextToeknRedis.class);

    @Value("${spring.application.name:app}")
    private String APP_NAME;

    private final String PREFIX_USER = "user:";

    @Autowired
    private QgAuthProperties qgAuthProperties;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public <T> T getUser(Class<T> clazz) {
        String key = getTokenString(getRequest());
        Object o = redisTemplate.opsForValue().get(key);
        if(o == null) {
            return null;
        }
        return (T)o;
    }

    @Override
    public Map getUser() {
        String key = getTokenString(getRequest());
        Object user = redisTemplate.opsForValue().get(key);
        if(user == null) {
            return null;
        }
        redisTemplate.expire(key,qgAuthProperties.getExpireTime(),TimeUnit.MILLISECONDS);
        return BeanUtil.beanToMap(user);
    }

    @Override
    public String getTokenString(HttpServletRequest request) {
        String flag = getRequest().getHeader(WebConstant.TOKEN);
        String key = PREFIX_USER + APP_NAME + ":" + flag;
        return key;
    }

    @Override
    public String setUser(Object user) {
        String flag = UUID.randomUUID().toString().substring(0,8);
        String key = PREFIX_USER + APP_NAME + ":" + flag;
        redisTemplate.opsForValue().set(key,user,qgAuthProperties.expireTime, TimeUnit.MILLISECONDS);
        return flag;
    }

    @Override
    public void setUser(String token) {
        logger.debug("该方法尚未实现，目前为空实现");
    }

    @Override
    public void removeUser() {
        String sessionId = getSession().getId();
        String key = PREFIX_USER + APP_NAME + ":" + sessionId;
        redisTemplate.delete(key);
    }
}
